<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员登录</title>
    <link rel="stylesheet" href="../static/css/public.css">

</head>

<body>
    <div>
        <form action="/loginDone" class="public" method="POST" id="loginForm">
            <h1>后台管理员登录</h1>

            <input type="text" placeholder="用户名" name="username" id="username">
            <input type="password" placeholder="密码" name="password" id="password">
            <div class="alert alert-light text-center invisible" role="alert">

                <font id="msgId"></font> <small id="comment" class="form-text text-muted">{{msg}}</small>
            </div>

            <input type="button" class="btn" value="立即登录" onclick="login()">
            <div>
                <a onclick="user()">普通用户登录</a> |
                <a onclick="register()">注册</a>

            </div>


        </form>

    </div>
    <script src="../static/js/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
    <script src="../static/js/bootstrap.min.js"></script>
    <script>
        //普通用户登录
        function user() {
            window.location.href = '/user';
        }

        //注册
        function register() {
            window.location.href = '/register';
        }

        //登录
        function login() {

            //获取表单数据
            let uid = $('#username').val();
            let pwd = $('#password').val();


            //在前端判断用户名、密码是否为空，为空则提示；不为空则向服务器提交
            if (uid.length > 0 && pwd.length > 0) {
                axios({
                    method: 'post',
                    url: '/loginDone',
                    data: $('#loginForm').serialize(),
                }).then(function (res) {
                    // axios工具下，服务器真正返回的数据在返回对象的data中
                    console.log(res);
                    res = res.data;
                    if (res.code === 200) {
                        window.location.href = '/manager';
                    } else {
                        alert_fn(res.msg);
                        console.log(res.msg);
                    }
                }).catch((err) => {
                     alert_fn(err);
                    console.log(err);
                });
            } else {
                alert_fn('用户名和密码不能为空');
            }
        }

        //包装消息警告框(显示和隐藏)

        function alert_fn(msg) {
            $('#msgId').text(msg);
            $('.alert').removeClass('invisible');
            setTimeout(() => {
                $('.alert').addClass('invisible');
            }, 3000);
        }

    </script>
</body>

</html>